package com.xhwl.centiotdata.handler.org.impl;

import com.xhwl.centiotdata.handler.account.impl.AccountLeopenHandler;
import com.xhwl.centiotdata.handler.org.OrgFactory;
import com.xhwl.centiotdata.handler.org.OrgHandler;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.IOrgInfoService;
import com.xhwl.centiotdata.service.cent.IProjectCentService;
import com.xhwl.centiotdata.suppliersystem.leopen.RegionLeopenHandler;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author pengjunming
 * @description
 * @date 2023/2/11 14:37
 */
@Slf4j
@Service
public class OrgLeopenHandler extends OrgHandler {

    @Resource
    private RegionLeopenHandler regionLeopenHandler;

    @Resource
    private IOrgInfoService iOrgInfoService;

    @Autowired
    IProjectCentService iProjectCentService;

    @Autowired
    private AccountLeopenHandler accountLeopenHandler;

    @Override
    public void createOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        log.info("==组织数据同步乐牛");
        HashMap<Integer, String> parent = new HashMap<>();
        //查询乐牛组织第三方记录
        List<OrgInfo> orgInfoList = iOrgInfoService.getList(config.getProductId(), null);
        Integer enterpriseId = organizations.get(0).getEnterpriseId();
        Short industryId = organizations.get(0).getIndustryId();
        //查询企业（组织根节点）
        OrganizationQuery query = new OrganizationQuery();
        query.setEnterpriseId(enterpriseId);
        query.setTypes(Arrays.asList(OrganizationTypeEnum.ENTERPRISE.getId().intValue()));
        List<Organization> organizationListMap = iProjectCentService.organizationList(query);
        parent.put(organizationListMap.get(0).getParentId(), "1");
        //企业组织节点第三方记录处理
        OrgInfo result = orgInfoList.stream().filter(s -> s.getId().equals(organizationListMap.get(0).getId())).findAny().orElse(null);
        if (null != result && StringUtils.isNotEmpty(result.getOrgIndexCode())) {
            parent.put(organizationListMap.get(0).getId(), result.getOrgIndexCode());
        } else {
            OrgInfo orgInfo = syncOrg(organizationListMap.get(0), config, parent);
            parent.put(organizationListMap.get(0).getId(), orgInfo.getOrgIndexCode());
            iOrgInfoService.save(orgInfo);
        }
        //组织数据处理
        query.setTypes(Collections.singletonList(OrganizationTypeEnum.ORG.getId().intValue()));
        List<Organization> organizationAreaList = iProjectCentService.organizationList(query);
        if (!CollectionUtils.isEmpty(organizationAreaList)) {
            List<OrgInfo> tmpList = new ArrayList<>();
            organizationAreaList.forEach(org -> {
                OrgInfo tmpOrg = orgInfoList.stream().filter(s -> s.getId().equals(org.getId())).findAny().orElse(null);
                if (null != tmpOrg && StringUtils.isNotEmpty(tmpOrg.getOrgIndexCode())) {
                    parent.put(org.getId(), tmpOrg.getOrgIndexCode());
                } else {
                    OrgInfo orgInfoTemp = syncOrg(org, config, parent);
                    if (orgInfoTemp != null) {
                        tmpList.add(orgInfoTemp);
                        parent.put(org.getId(), orgInfoTemp.getOrgIndexCode());
                    }
                }
            });
            iOrgInfoService.saveBatch(tmpList);
        }
    }

    private OrgInfo syncOrg(Organization org, PedestrianIntegrationConfigDTO config, HashMap<Integer, String> parent) {
        if (StringUtils.isNotEmpty(parent.getOrDefault(org.getParentId(), ""))) {
            Organization organization = new Organization();
            organization.setName(org.getName());
            organization.setParentId(Integer.parseInt(parent.get(org.getParentId())));
            if(regionLeopenHandler.createOrg(config, organization)){
                OrgInfo orgInfo = new OrgInfo();
                orgInfo.setId(org.getId());
                orgInfo.setParentId(org.getParentId());
                orgInfo.setProductId(config.getProductId());
                orgInfo.setOrgName(org.getName());
                orgInfo.setOrgIndexCode(org.getId().toString());//乐牛新增组织不返回成功的组织id，直接用星启的组织id映射
                return orgInfo;
            }
        }
        return null;
    }

    @Override
    public void updateOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        for (Organization org : organizations) {
            if (org.getType() == OrganizationTypeEnum.ORG.getId().intValue()) {
                OrgInfo orgInfo = iOrgInfoService.getOrgInfo(org.getId(), config.getProductId());
                orgInfo.setOrgName(org.getName());
                regionLeopenHandler.updateOrg(config, orgInfo);
                iOrgInfoService.updateOrgInfo(orgInfo);
            }
        }
    }

    @Override
    public void deleteOrg(PedestrianIntegrationConfigDTO config, List<Organization> organizations) {
        List<Integer> ids = organizations.stream().filter(org -> org.getType() == OrganizationTypeEnum.ORG.getId().intValue())
                .map(Organization::getId).collect(Collectors.toList());
        List<OrgInfo> orgInfos = iOrgInfoService.getList(config.getProductId(), ids);
        if (CollectionUtils.isNotEmpty(orgInfos)) {
            regionLeopenHandler.deleteOrg(config, orgInfos);
            orgInfos.forEach(orgInfo -> iOrgInfoService.deleteOrgInfo(orgInfo.getId(), orgInfo.getProductId()));
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        OrgFactory.register(ProductEnum.LEOPEN.id, this);
    }
}
